// 初始化称号系统
document.addEventListener('DOMContentLoaded', function() {
    // 获取称号数据
    fetch('get_titles.php')
        .then(response => response.json())
        .then(titlesData => {
            window.userTitles = titlesData;
            enhanceMessages();
            observeNewMessages();
        })
        .catch(error => {
            console.error('获取称号数据失败:', error);
        });
});

// 增强现有消息
function enhanceMessages() {
    const messages = document.querySelectorAll('.message');
    messages.forEach(message => {
        if (message.dataset.titlesEnhanced) return;
        
        const usernameElement = message.querySelector('.user-name');
        if (usernameElement) {
            const username = usernameElement.textContent;
            const titlesHtml = renderUserTitles(username);
            if (titlesHtml) {
                const titlesContainer = document.createElement('div');
                titlesContainer.className = 'titles-container';
                titlesContainer.innerHTML = titlesHtml;
                usernameElement.parentNode.insertBefore(titlesContainer, usernameElement.nextSibling);
            }
        }
        message.dataset.titlesEnhanced = true;
    });
}

// 渲染用户称号
function renderUserTitles(username) {
    if (!window.userTitles || !window.userTitles[username]) {
        return '';
    }
    
    const titles = window.userTitles[username];
    let html = '';
    
    titles.forEach(title => {
        html += `<span class="user-title" style="background: ${title.color}">${title.name}</span>`;
    });
    
    return html;
}

// 监听新消息
function observeNewMessages() {
    const chatContainer = document.getElementById('chat-container');
    if (!chatContainer) return;
    
    const observer = new MutationObserver(mutations => {
        mutations.forEach(mutation => {
            if (mutation.addedNodes.length) {
                enhanceMessages();
            }
        });
    });
    
    observer.observe(chatContainer, { childList: true });
}